﻿using AGVController.BaseClass;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using UE.Net.Sockets;

namespace AGVController
{
    public class ServiceAgvPush
    {
        /// <summary>
        /// 报警码编号
        /// </summary>
        private string _agvIp { get; set; }
        /// <summary>
        ///报警发生时间 
        /// </summary>
        private int _agvPort { get; set; }
        public delegate void GetAgvStatusDelegateHander(AgvModel.robot_config_push_res rp);
        public event GetAgvStatusDelegateHander GetAgvStatus;
        AsyncTcpClient asyncTcpClient;
        public ServiceAgvPush(string agvIp, int agvPort)
        {
            _agvIp = agvIp;
            _agvPort = agvPort;

            //AgvModel.robot_config_push_res rptest = new AgvModel.robot_config_push_res();
            //rptest.target_id = "AAA";
            //string strrp= Newtonsoft.Json.JsonConvert.SerializeObject(rptest);
            //byte[] btest = Common.normalStrToHexByte(strrp);
            //SeerMessageHead smh = new SeerMessageHead();
            //smh.sync = 0x5A;
            //smh.version = 0x01;
            //smh.number = 1;
            //smh.length = (uint)btest.Length;
            //smh.type = 0x4B65;
            //byte[] bhead = Common.seerMessageHeadToBytes(smh);

            //byte[] bAll = bhead.Concat(btest).ToArray();

            //string hexString = BitConverter.ToString(bAll).Replace("-", " ");

            IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse(agvIp), agvPort);
            asyncTcpClient = new AsyncTcpClient(remoteEP);
            asyncTcpClient.ServerConnected += new EventHandler<TcpServerConnectedEventArgs>(client_ServerConnected);
            asyncTcpClient.ServerDisconnected += new EventHandler<TcpServerDisconnectedEventArgs>(client_ServerDisconnected);
            asyncTcpClient.DatagramReceived += new EventHandler<TcpDatagramReceivedEventArgs<byte[]>>(client_PlaintextReceived);
            asyncTcpClient.Connect();
        }

        void client_PlaintextReceived(object sender, TcpDatagramReceivedEventArgs<byte[]> e)
        {
            Console.Write(string.Format("Server : {0} --> ", e.TcpClient.Client.RemoteEndPoint.ToString()));
            Console.WriteLine(string.Format("{0}", Encoding.Default.GetString(e.Datagram)));
            if (e.Datagram[0] == 0x5A && e.Datagram.Length > 16)
            {
                byte[] inStreamHead = new byte[16];
                byte[] inStreamData = new byte[e.Datagram.Length - 16];
                int dataLen = 0;
                for (int i = 0; i < e.Datagram.Length; i++)
                {
                    if (i < 16)
                    {
                        inStreamHead[i] = e.Datagram[i];
                    }
                    else
                    {
                        inStreamData[i - 16] = e.Datagram[i];
                        dataLen = inStreamHead[6] * 256 + inStreamHead[7];
                        if (i >= (16+ dataLen)) break;
                    }
                }
                byte[] inStreamDataOnceRead = new byte[dataLen];
                Array.Copy(inStreamData, 0, inStreamDataOnceRead,0, dataLen);
                SaveLog(BitConverter.ToString(inStreamHead).Replace("-", " ") + " " + BitConverter.ToString(inStreamData).Replace("-", " ") + "=" + Encoding.UTF8.GetString(inStreamDataOnceRead));


                //var recv_head = Common.bytesToStructure<SeerMessageHead>(inStreamHead);
                //byte[] recvbyte = BitConverter.GetBytes(recv_head.length);
                //Array.Reverse(recvbyte);





                if ((inStreamHead[8] * 256 + inStreamHead[9]) == 0x4B65)
                {
                    string str = Encoding.UTF8.GetString(inStreamDataOnceRead);
                    AgvModel.robot_config_push_res rcps = Newtonsoft.Json.JsonConvert.DeserializeObject<AgvModel.robot_config_push_res>(str);
                     
                    GetAgvStatus?.Invoke(rcps); 
                }
            }
        }

        void client_ServerConnected(object sender, TcpServerConnectedEventArgs e)
        {
            Console.WriteLine("AGV推送端口连接成功");
        }

        void client_ServerDisconnected(object sender, TcpServerDisconnectedEventArgs e)
        {
            Console.WriteLine("AGV推送端口断开连接");



        }
        #region ADD BY CJH


        #region 给机器人发送指令 

        //public string SendToAgv(SeerMessageHead head, byte[] data)
        //{
        //    string strResult = "";
        //    try
        //    {
        //        if (Client.Connected)
        //        {
        //            NetworkStream serverStream = Client.GetStream();

        //            var newmsg = new SeerMessage();

        //            newmsg.head = head;
        //            newmsg.data = data;

        //            serverStream.Write(Common.seerMessageHeadToBytes(newmsg.head), 0, Marshal.SizeOf(newmsg.head));
        //            serverStream.Write(newmsg.data, 0, newmsg.data.Length);
        //            serverStream.Flush();

        //            byte[] inStream = new byte[16];
        //            while (16 != serverStream.Read(inStream, 0, 16))
        //            {
        //                Thread.Sleep(20);
        //            }

        //            var recv_head = Common.bytesToStructure<SeerMessageHead>(inStream);

        //            byte[] recvbyte = BitConverter.GetBytes(recv_head.length);

        //            Array.Reverse(recvbyte);

        //            var dsize = BitConverter.ToUInt32(recvbyte, 0);

        //            const int bufferSize = 512;
        //            List<byte> datalist = new List<byte>();
        //            int count = 0;

        //            while (true)
        //            {
        //                byte[] buffer = new byte[bufferSize];
        //                int readSize = serverStream.Read(buffer, 0, bufferSize);

        //                count += readSize;
        //                datalist.AddRange(buffer);

        //                if (count == dsize)
        //                {
        //                    break;
        //                }

        //                Thread.Sleep(10);
        //            }

        //            //textBox_recv_head.Text = BitConverter.ToString(seerMessageHeadToBytes(recv_head)).Replace("-", " ");//normalStrToHexStr(Encoding.UTF8.GetString(seerMessageHeadToBytes(recv_head)));

        //            string str = Encoding.UTF8.GetString(datalist.ToArray());

        //            //textBox_recv_data.Invoke(new EventHandler(delegate { textBox_recv_data.Text = str; }));

        //            //Client.Close();

        //            strResult=str;
        //        }
        //    }
        //    catch (SocketException)
        //    {
        //        //textBox_recv_data.Invoke(new EventHandler(delegate { textBox_recv_data.Text = ""; }));
        //        //MessageBox.Show("Connect Error!");
        //        strResult= "ConnectError";
        //    }
        //    catch (IOException)
        //    {
        //        //textBox_recv_data.Invoke(new EventHandler(delegate { textBox_recv_data.Text = ""; }));
        //        //MessageBox.Show("");

        //        strResult = "IOException";
        //    }
        //    return strResult;
        //}


        #endregion

        #endregion


        private void SaveLog(string logMsg)
        {
            string path = @"C:\agvLogpush.txt";

            using (StreamWriter writer = new StreamWriter(path, true)) // true 表示追加模式
            {
                writer.WriteLine(logMsg);
            }
        }
    }

}
